import pymysql


class User(object):
    def __init__(self, user_id, username, balance):
        self.user_id = user_id
        self.username = username
        self.balance = balance


class SQLHelper(object):

    def __init__(self):
        self.conn = pymysql.connect(
            host="127.0.0.1",
            port=3306,
            user='root',
            password='root',
            database='csdn_bank',
            charset='utf8'
        )
        self.cursor = self.conn.cursor()

    def helper_login(self, username, password):
        sql = "select id,username,balance from users where username='{}' and password='{}'".format(username, password)
        self.cursor.execute(sql)
        result = self.cursor.fetchone()
        if result:
            user_id = result[0]
            username = result[1]
            balance = result[2]
            user = User(user_id=user_id, username=username, balance=balance)
            return user
        else:
            return False

    def helper_deposit(self, user, money):
        updated_balance = user.balance + money
        try:
            sql = "update users set balance={} where id={}".format(updated_balance, user.user_id)
            self.cursor.execute(sql)
            self.conn.commit()
            user.balance += money
            return True
        except:
            return False

    def helper_withdraw(self, user, money):
        if user.balance < money:
            return False
        updated_balance = user.balance - money
        sql = "update users set balance={} where id={}".format(updated_balance, user.user_id)
        try:
            self.cursor.execute(sql)
            self.conn.commit()
            user.balance -= money
            return True
        except:
            return False

    def __del__(self):
        self.conn.close()


class Bank(object):
    """
    用来管理银行系统业务的
    """

    def __init__(self):
        self.helper = SQLHelper()
        self.user = None

    def deposit(self):
        money = int(input("请输入要存储的金额："))
        result = self.helper.helper_deposit(self.user, money)
        if result:
            print("恭喜！%d元存储成功！余额为%d" % (money, self.user.balance))
        else:
            print("系统原因，存钱失败！")

    def withdraw(self):
        money = int(input("请输入要提取的金额："))
        result = self.helper.helper_withdraw(self.user, money)
        if not result:
            print("取钱失败！")
        else:
            print("恭喜！%d元提取成功！余额为%d" % (money, self.user.balance))

    def balance(self):
        print("您的余额为：%d" % (self.user.balance))

    def index(self):
        print("欢迎来到CSDN银行！")
        while True:
            print("欢迎进入ICBC交易系统！")
            print("1. 存钱")
            print("2. 取钱")
            print("3. 查看余额")
            print("0. 退出系统")
            option = input("请输入选择：")
            if option == '1':
                self.deposit()
            elif option == '2':
                self.withdraw()
            elif option == '3':
                self.balance()
            elif option == '0':
                exit(0)
            else:
                print("您的输入有误，请重新输入！")

    def login(self):
        print("请先登录！")
        login_times = 0
        while True:
            username = input("请输入用户名：")
            password = input("请输入密码：")
            user = self.helper.helper_login(username, password)
            if user:
                self.user = user
                return True
            else:
                print("用户名或密码错误！")
                login_times += 1
                if login_times >= 3:
                    return False

    def run(self):
        if self.login():
            self.index()


def main():
    bank = Bank()
    bank.run()


if __name__ == '__main__':
    main()
